<?php

namespace Hx\Mvc\Controller;

use Hx\App;
use Hx\Di;

/**
 * 控制器基类
 * Class Controller
 * @package Hx\Mvc
 * @property \Hx\Http\Request request
 * @property \Hx\Http\Response response
 * @property \Hx\Http\Input input
 * @property string viewClass
 * @property \Hx\Mvc\View\Base view
 */
abstract class Base extends Di {

    /**
     * 设置视图类
     * @param string $name
     */
    protected function setView($name = 'Hx\Mvc\View\Simple:view') {
        if (isset($this->viewClass)) {
            return $this->set('view', $this->viewClass, TRUE);
        }
        return $this->set('view', $name, TRUE);
    }

    /**
     * @param int $code
     * @param null|string $message
     * @return \Hx\Mvc\View\Base|\Hx\Http\Response
     */
    protected function setError($code, $message = NULL) {
        if (!$message) {
            $message = $this->response->getStatusText($code);
        }
        $this->response->setStatus($code);
        if (isset($this->view) && $this->view->hasTemplate('error')) {
            return $this->view->assign('message', $message)
                ->setTemplate('error');
        }
        return $this->response->setBody($message);
    }

    /**
     * 魔术方法获取实例
     * @param string $name
     * @return mixed|NULL
     */
    public function __get($name) {
        if ($name === 'view') {
            return $this->setView();
        }
        if ($name === 'request') {
            return $this->set('request', 'Hx\Http\Request');
        }
        if ($name === 'response') {
            return $this->set('response', 'Hx\Http\Response');
        }
        if ($name === 'input') {
            return $this->set('input', 'Hx\Http\Input');
        }
        if (strstr($name, 'Model')) {
            $modelName = App::getInstance()->getName() . '\Model\\' . ucfirst(rtrim($name, 'Model'));
            return $this->set($name, $modelName);
        }
        return NULL;
    }


}